package com.mao.controller;

import com.mao.pojo.Department;
import com.mao.pojo.Employee;
import com.mao.service.DepartmentService;
import com.mao.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
    @Autowired
    DepartmentService departmentService;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeService.getAllEmployee();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddPage(Model model){
        //查出所有部门的信息
        Collection<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee){
        //添加的操作
        employeeService.save(employee);//调用底层业务，保存员工的信息
//        System.out.println(employee);
        return "redirect:/emps";
    }

    //去员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id")int id,Model model){
//        System.out.println(id);
        Employee employee = employeeService.getEmployeeById(id);
//        System.out.println(employee.getDepartment());
//        System.out.println(employee.getDepartment().getId());
        model.addAttribute("emp",employee);
        Collection<Department> departments = departmentService.getDepartments();
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    @PostMapping("updateEmp")
    public String updateEmp(Employee employee){
        System.out.println(employee);
        employeeService.updateEmployee(employee);
        return "redirect:/emps";
    }
    @RequestMapping("/deleteEmp/{id}")
    public String deleteEmp(@PathVariable("id")int id){
        employeeService.delete(id);
        return "redirect:/emps";
    }

}
